<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import * as accountApi from '@/api/account'
import * as questionAnswerApi from '@/api/questionAnswer'

import { message } from 'ant-design-vue'
import EditText from './EditText.vue'
import EditTemplate from './EditTemplate.vue'

const editTextRef = ref()
const editTemplateRef = ref()

const tabFlag = ref<boolean>(true)
const tableData = ref([])

// 选择微信账号/选择闲鱼账号后
let loading = ref<boolean>(false)
const dataSource = ref<any>([])
const columns = [
  {
    title: '名称',
    key: 'theTitle',
    width: 150,
  },
  {
    title: '内容',
    key: 'theContent',
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
]

const getList = async (robotId: string) => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await questionAnswerApi.getFishScriptList({
      robotId,
    })
    if (state === 200) {
      dataSource.value = data
      tableData.value = dataSource.value
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 话术模板
const dataSourceCopy = ref<any>([])
const getWechartScriptTemplate = async () => {
  tabFlag.value = true
  try {
    let { state, data, message: msg } = await questionAnswerApi.getWechartScriptTemplate()
    if (state === 200) {
      dataSourceCopy.value = data
      tableData.value = dataSourceCopy.value
      // console.log('dataSourceCopy=', dataSourceCopy.value)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 修改模板
const editTemplate = (record: object) => {
  editTemplateRef.value.showModal(record)
}

onMounted(() => {
  getRobatList()
  getGroupList()
  // getWechartScriptTemplate()
})

// okRobat：机器人id
const editText = (record: object) => {
  editTextRef.value.showModal(record)
}
const setTableList = (row: any) => {
  dataSource.value = dataSource.value.map(item => {
    if (item.id == row.id) {
      item.contentTemplate = row.content
    }
    // item.title = item.titleNum
    return item
  })
}

// 拉取机器人列表123
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'
const robatList = ref<SelectProps['options']>([])
const options = ref<SelectProps['options']>([])
const groupList = ref<SelectProps['options']>([])
const groupId = ref<string>()
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotGroupList()
    if (state === 200) {
      groupList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectGroup = (selectValue: unknown) => {
  groupId.value = selectValue as string
  sendRobat.value = options.value
    .filter(item => item.groupId == groupId.value)
    .map(element => element.id)
}
const getRobatList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getFishRobotList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })

      options.value = data.list

      if (data.list.length == 0) {
        message.error('闲鱼：无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  getList(okRobat.value)
  tabFlag.value = false
}

// 推送配置
let sendRobat = ref<string>()
const selectSendRobat = (selectValue: unknown) => {
  sendRobat.value = selectValue as string
  // console.log('sendRobat.value=', sendRobat.value)
}
const pushRobot = async () => {
  let list = dataSource.value.map(item => {
    return {
      ...item,
      title: item.titleNum,
    }
  })
  // console.log('list=', list)

  try {
    let { state, message: msg } = await questionAnswerApi.fishScriptPushArriveRobots({
      pushRobotId: okRobat.value,
      receiveRobotIds: sendRobat.value,
      scriptDtoList: list,
    })
    if (state === 200) {
      message.success('推送成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const sendOk = () => pushRobot()

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}
</script>

<template>
  <div style="margin: 5px 0; text-align: right">
    <span>选择闲鱼账号：</span>
    <a-select
      v-model:value="okRobat"
      @change="selectRobat"
      placeholder="请选择"
      style="width: 150px; text-align: left"
      show-search
      :options="optionList"
      :filter-option="filterOption"
    >
      <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
  </div>
  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :pagination="false"
    :data-source="tableData"
    :loading="loading"
  >
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'theTitle'">
        <span>名称</span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'theTitle'">
        <div style="width: 150px">{{ record.title }}</div>
      </template>

      <template v-if="column.key === 'theContent'">
        <a-popover>
          <template #content>
            <div>
              {{ record.contentTemplate }}
            </div>
          </template>
          <div class="hiddenText">
            {{ record.contentTemplate }}
          </div>
        </a-popover>
      </template>

      <template v-else-if="column.key === 'action'">
        <div style="width: 120px; margin: 0; padding: 0">
          <a v-if="!tabFlag" @click="editText(record)">修改</a>
          <a v-if="tabFlag" @click="editTemplate(record)">修改</a>
        </div>
      </template>
    </template>
  </a-table>

  <!-- 推送 -->
  <div style="margin: 5px 0">
    <span>选择推送闲鱼账号：</span>
    <a-select
      v-model:value="groupId"
      @change="selectGroup"
      placeholder="请选择分组"
      style="width: 6%; text-align: left"
    >
      <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
        {{ item.groupName }}
      </a-select-option>
    </a-select>
    <a-select
      mode="multiple"
      v-model:value="sendRobat"
      @change="selectSendRobat"
      placeholder="请选择"
      style="width: 40%; text-align: left; margin-left: 5px"
      allowClear
      show-search
      :options="optionList"
      :filter-option="filterOption"
    >
      <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
    <a-button type="primary" style="margin-left: 10px; border-radius: 6px" @click="sendOk">
      确认推送
    </a-button>
  </div>

  <EditText ref="editTextRef" @refresh="setTableList"></EditText>
  <EditTemplate ref="editTemplateRef"></EditTemplate>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 1000px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

a:hover {
  color: red;
}
</style>
